module robot_leg (clk,write_data,clr_n,pwm_out,cs); 
input clk; 
input [7:0] write_data;
//input [2:0]write_n;
input clr_n;
input cs;
output [2:0]pwm_out;
//output [7:0] counte;
wire read_data;
reg clkin;
reg [1:0]wrcount;
reg [1:0]rdcount;
reg [1:0]sel;
reg rd;
reg rd_over;
reg wr;
reg wr_over;
reg pwm_en;
wire cs;
wire [7:0]outputdata;
reg [7:0]counter; 
reg [7:0]write_data0;
reg [7:0]write_data1;
reg [7:0]write_data2;

parameter change_para = 8'h32;  

legfifo fifo(
				.clock(clk),
				.data(write_data),
				.rdreq(rd),
				.wrreq(wr),
				.empty(),
				.q(outputdata),
				.usedw()
				);
pwm p0(
		.clk(clkin),
		.write_data(write_data0),
		.cs(pwm_en),
		.clr_n(clr_n),
		.read_data(read_data),
		.pwm_out(pwm_out[0])
		);
pwm p1(
		.clk(clkin),
		.write_data(write_data1),
		.cs(pwm_en),
		.clr_n(clr_n),
		.read_data(read_data),
		.pwm_out(pwm_out[1])
		);
pwm p2(
		.clk(clkin),
		.write_data(write_data2),
		.cs(pwm_en),
		.clr_n(clr_n),
		.read_data(read_data),
		.pwm_out(pwm_out[2])
		);

//閸掑棝顣堕崳	
always@(posedge clk or negedge clr_n)	
begin
if(clr_n == 0)
	begin
		counter <= 8'h00;
		clkin <=0;
	end
else if(counter >= change_para - 1)
	begin
		clkin <= ~clkin;
		counter <= 0;
	end
else
	begin
		counter <= counter +1;
		clkin <= clkin;
	end
end	
//fifo鐠囩粯甯堕崚
always @(posedge clk or negedge clr_n)
begin
	if(clr_n == 0)
		begin
			write_data0 <= 8'h00;
			write_data2 <= 8'h00;
			write_data1 <= 8'h00;
		end
	else if(rd == 1)
		begin
			write_data0 <= outputdata;
			write_data1 <= write_data0;
			write_data2 <= write_data1;
		end
	else
		begin
			write_data0 <= write_data0;
			write_data1 <= write_data1;
			write_data2 <= write_data2;
		end
end
always@(negedge rd_over or negedge cs)	
	begin
		if(cs == 0)
			pwm_en <= 0;
		else if(clr_n == 0)
			pwm_en <= 0;
		else
			pwm_en <= 1;	
	end
always @(posedge clk or negedge clr_n)
begin
	if(clr_n == 0)
		begin
			rdcount = 0;
			rd_over <= 0;
		end
	else if(rd == 0)
		begin
			rdcount = 0;
			rd_over <= 0;
		end
	else if(rdcount >= 2)
		begin
			rd_over <= 1;
			rdcount <= 0;
		end
	else
		rdcount <= rdcount+1;
end
//fifo閸愭瑦甯堕崚
always @(posedge clk or negedge clr_n )
begin
	if(clr_n == 0)
		wr <= 0;
	else if((cs == 1)&(wr_over == 0))
		wr <= 1;			//wr閹貉冨煑
	else
		wr <= 0;
end
always @(posedge clk or negedge clr_n)
begin
	if(clr_n == 0)
		begin
			wrcount <= 0;
			wr_over <= 0;
			rd <= 0;
		end
	else if((wr == 0)&(rd_over == 1))
		begin
			wrcount <= 0;
			rd <= 0;
		end 
	else if(cs == 0)
			wr_over <= 0;
	else if(wr == 0)
			wrcount <= 0;
	else if(wrcount >= 1)
		begin
			rd <= 1;		//rd閹貉冨煑
			wrcount <= 0;
			wr_over <= 1;
		end
	else
		begin
			wrcount <= wrcount+1;
		end
end
endmodule